<?php

class FormElement_DateTime extends FormElement
{

  public $default;

  public function render($row, $action)
  {
    switch ($action) {
      case Form::ACTION_EDIT :
      case Form::ACTION_CREATE :
        $this->set('formatedValue', $this->getFormated($row));

        $output = parent::render($row, $action);

        break;

      default :
        $output = parent::render($row, $action);
    }

    return $output;
  }

  protected function getValue(&$row)
  {
    if (! isset($row[$this->getField()])) {
      return $this->default;
    }

    return $row[$this->getField()];
  }

  protected function getDisplayValue(&$row)
  {
    return $this->getFormated($row);
  }

  protected function getFormated(&$row)
  {
    return date('d/m/Y H:i:s', strtotime($this->getValue($row)));
  }

  public function setDataFromPost(&$row, $post, $action)
  {
    $date = $post->get($this->getField());

    if (function_exists('date_parse_from_format')) {
      $dt = date_parse_from_format('d/m/Y H:i:s', $date);
      $dt = mktime($dt['hour'], $dt['minute'], $dt['second'], $dt['month'], $dt['day'], $dt['year']);

      $value = date('Y-m-d H:i:s', $dt);
    }
    elseif (function_exists('strptime')) {
      $dt = strptime($date, 'd/m/Y H:i:s');

      $value = date('Y-m-d H:i:s', $dt);
    }
    else {
      $parts = explode(' ', $date);

      $date = explode('/', $parts[0]);

      $d = $date[0];
      $m = $date[1];
      $Y = $date[2];

      $value = "$Y-$m-$d $parts[1]";
    }

    $this->setValue($row, $value);
  }

}

?>